package com.wus.system.controller;

import com.wus.common.core.domain.base.Result;
import com.wus.system.request.TestXssReq;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;

/**
 * @Description: 测试类
 * @Author: wus
 * @Date: 2024/12/24 18:05
 */
@Tag(name = "测试管理")
@RequiredArgsConstructor
@RequestMapping("/test")
@RestController
public class TestController {

    private final Logger logger = LoggerFactory.getLogger(TestController.class);

    private final RedisTemplate<String, Object> redisTemplate;

    private final CacheManager cacheManager;

    @Operation(summary = "XSS测试接口")
    @PostMapping("/testXss")
    public Result<String> test(@RequestBody TestXssReq testXssReq) {
        // {
        //    "body": "<script>alert(1);</script>"
        //  }
        logger.info("查看脚本是否已被转换：testXssReq={}", testXssReq);
        return Result.ok(testXssReq.getBody());
    }

    @Operation(summary = "get缓存测试")
    @Cacheable(cacheNames = "test", key = "#id")
    @GetMapping("/cacheData/{id}")
    public Result<String> getCacheData(@PathVariable("id") Long id) {
        logger.info("---cacheData");

        // 测试redisTemplate操作，其他缓存类型灵活等操作可用redisTemplate
        redisTemplate.opsForValue().set("redis:test", "yes", Duration.ofMinutes(30));
        logger.info("---redis:test={}", redisTemplate.opsForValue().get("redis:test"));

        return Result.ok("yes");
    }

    @Operation(summary = "put缓存测试")
    @CachePut(cacheNames = "test", key = "#id")
    @PutMapping("/cacheData/{id}")
    public Result<String> putCacheData(@PathVariable("id") Long id) {
        // 灵活删除等操作，可通过cacheManager直接操作
        logger.info("---通过cacheManager直接取={}", cacheManager.getCache("test").get(id, Result.class));
        return Result.ok("no");
    }

    @Operation(summary = "delete缓存测试")
    @CacheEvict(cacheNames = "test", key = "#id")
    @DeleteMapping("/cacheData/{id}")
    public Result<Boolean> deleteCacheData(@PathVariable("id") Long id) {
        return Result.ok(true);
    }
}
